import { useEffect, useCallback, useState } from 'react';
import { useDispatch, useSelector, shallowEqual } from 'react-redux';
import {
  DATA_FETCH_DATA_BEGIN,
  DATA_FETCH_DATA_SUCCESS,
  DATA_FETCH_DATA_FAILURE,
  DATA_FETCH_DATA_DISMISS_ERROR,
} from './constants';
import { requests } from '../../common/request';


export function fetchData(code, args = {}) {
  return (dispatch) => { // optionally you can have getState as the second argument
    dispatch({
      type: DATA_FETCH_DATA_BEGIN,
      code
    });

    const promise = new Promise((resolve, reject) => {
      const doRequest = requests.fetchData(code, { params: args })

      doRequest.then(
        (res) => {
          dispatch({
            type: DATA_FETCH_DATA_SUCCESS,
            data: res,
            code
          });
          resolve(res);
        },
        // Use rejectHandler as the second argument so that render errors won't be caught.
        (err) => {
          dispatch({
            type: DATA_FETCH_DATA_FAILURE,
            data: { error: err },
            code
          });
          reject(err);
        },
      );
    });

    return promise;
  };
}

export function dismissFetchDataError() {
  return {
    type: DATA_FETCH_DATA_DISMISS_ERROR,
  };
}

export function useFetchData(code, pageId) {

  const dispatch = useDispatch();

  const { module, request, pageData } = useSelector(
    state => ({
      module: state.data["module" + code] || {},
      request: state.data["request" + code] || {},
      pageData: state.data["page" + pageId] || {}
    })
    // , shallowEqual
  );

  const boundAction = useCallback((...args) => {
    return dispatch(fetchData(code, ...args)).then(res => {
      console.log('%c 🥕 res: ', 'font-size:20px;background-color: #EA7E5C;color:#fff;', res);
    }).catch(error => {
      console.error('%c 🥃 error: ', 'font-size:20px;background-color: #7F2B82;color:#fff;', error);
    })
  }, [dispatch, code]);

  const boundDismissError = useCallback(() => {
    return dispatch(dismissFetchDataError());
  }, [dispatch]);

  // 联动
  useEffect(() => {
    console.log('%c 🍟 useEffect: ', 'font-size:20px;background-color: #2EAFB0;color:#fff;');
    // boundAction(request.params)
    return () => {
    }
  }, [])



  // 自动处理请求
  useEffect(() => {
    console.log('%c 🌭 useEffect: ', 'font-size:20px;background-color: #B03734;color:#fff;');
    boundAction(request.params)
    return () => {
    }
  }, [boundAction, request.params])

  return {
    module,
    request,
    pageData,
    status: request.status,
    fetchData: boundAction,
    dismissFetchDataError: boundDismissError,
  };
}

export function reducer(state, action) {
  switch (action.type) {
    case DATA_FETCH_DATA_BEGIN:
      // Just after a request is sent
      {
        let request = state["request" + action.code] || {}
        request.status = "loading"
        state.request[action.code] = request
        return {
          ...state,
        };
      }
    case DATA_FETCH_DATA_SUCCESS:
      // The request is success
      {
        let status = "show"
        let request = state["request" + action.code] || {}
        request.status = status
        request.data = action.data

        return {
          ...state,
        };
      }
    case DATA_FETCH_DATA_FAILURE:
      // The request is failed
      return {
        ...state,
        // fetchDataPending: false,
        // fetchDataError: action.data.error,
      };

    case DATA_FETCH_DATA_DISMISS_ERROR:
      // Dismiss the request failure error
      return {
        ...state,
        // fetchDataError: null,
      };

    default:
      return state;
  }
}
